﻿using System.Web.Mvc;
using BLL.Installer;
using BLL.Interface.User;
using BLL.Model.User;
using BLL.Utility;
using WayCloud.ViewModel;
using WayCloud.ViewModel.User;
using System.Linq;

namespace WayCloud.Controllers.User
{
    [Authorize(Roles = "admin")]
    public class UserController : Controller
    {
        private const string NewPassword = "123";

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult List(UserCondition condition)
        {
            AnalyseJqGridQueryString ajqs = new AnalyseJqGridQueryString(Request.QueryString);
            var page = ajqs.GetPageInfo();
            var sort = ajqs.GetSortField();
            var userInfoManager = ContainerHelper.Instance.Container.Resolve<IUserInfo>();
            var userInfoList = userInfoManager.GetUserInfoByFilter(condition, sort, page);
            var result = new JqGrid(page, userInfoList.Select(p => new
                                                                  {
                                                                      p.Id,
                                                                      p.AccountName,
                                                                      p.Email,
                                                                      p.Phone,
                                                                      p.UserName,
                                                                      Role = p.RoleList.Select(r => r.DisplayName).ToList()
                                                                  })
                                                         );
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult FindUserInfoById(int id)
        {
            var userInfoManager = ContainerHelper.Instance.Container.Resolve<IUserInfo>();
            var user = userInfoManager.FindUserInfoById(id);
            return View("Add", user);
        }

        public ActionResult Edit([Bind(Include = "Id,UserName,Email,Phone,IsAdmin")]UserInfo user)
        {
            if (!ModelState.IsValid)
            {
                return View("Add", user);
            }
            var userInfoManager = ContainerHelper.Instance.Container.Resolve<IUserInfo>();
            return Content(userInfoManager.UpdateUserInfo(user) ? "ok" : "error");
        }

        [HttpGet]
        public ActionResult ResetPassword(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return Content("error");
            }
            var userInfoManager = ContainerHelper.Instance.Container.Resolve<IUserInfo>();
            userInfoManager.ResetPassword(int.Parse(id), NewPassword);
            return Content(NewPassword);
        }

    }
}
